package com.hu.hutool.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.Locale;

/**
 * Handler 拦截器
 *
 * @Author CazCen
 * @Date 2021/11/22 11:32
 */
@Slf4j
@Component
public class HandlerInterceptorTest extends HandlerInterceptorAdapter {

    private final static Logger logger = LoggerFactory.getLogger(HandlerInterceptorTest.class);

    /**
     * 一般在校验用户信息的时候使用
     * 这样使用作为获取浏览器语言的设置，作为国际化使用,设置谷歌浏览器语言可以百度一下
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        logger.info("每次请求之前，都会先访问这里 request:{}", request);
        logger.info("每次请求之前，都会先访问这里 response:{}", response);

        String header = request.getHeader("Accept-Language");

        logger.info("header:{}", header);

        String[] split = header.split(",");

        String s = split[0];

        String[] split1 = s.split("-");

        String language = MessageFormat.format("{0}_{1}", split1[0], split1[1]);

        log.info("language:{}", language);

        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        logger.info("locale:{}", Locale.getDefault());

        return true;
    }
}
